package org.fle4y.example.aio.chat;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;
import org.fle4y.common.utils.log.LogUtil;
import org.fle4y.framework.net.LogicHandler;
import org.fle4y.framework.net.Message;
import org.fle4y.framework.net.Session;
import org.fle4y.framework.net.aio.AIOServer;
import org.fle4y.framework.net.aio.AIOSession;

/**
 * author : xiehui<br>
 * company : northking <br>
 * Create at: 2012-6-13<br>
 * @version : 1.0<br>
 * mailto:flexie@foxmail.com<br>
 *  Description :
 */
public class ChatLogicHandler implements LogicHandler{
	private AIOServer server;
	private static final Logger log =LogUtil.getLogger(ChatLogicHandler.class.getName());
	private Vector<String> names=new Vector<String>();
	public void doLogic(AIOSession session,
			LinkedBlockingQueue<Message> input,LinkedBlockingQueue<Message> output) {
		ConcurrentHashMap<Long,Session> sessionMap=server.getSessionMap();
		
		ChatMessage msg;
		log.info("会话池size ："+sessionMap.size());
		try {
			while((msg = (ChatMessage) input.take())!=null)
			{
				if(msg.getType().equals(ChatType.LOGIN)){
					session.setAttribute("userName",msg.getName());
					names.add(msg.getName());
					for(Session s:sessionMap.values()){
						ChatMessage freshName= new ChatMessage();
						freshName.setType(ChatType.FRESH);
						freshName.setName(msg.getName());
						String strs="";
						for(int i=0;i<names.size();i++){
							strs+=names.get(i)+"@";
						}
						freshName.setMessage(strs);
						freshName.setContent(ByteBuffer.wrap(freshName.toString().getBytes(Charset.forName("UTF-8"))));
						s.add(freshName);
					}
				}else if(msg.getType().equals(ChatType.CHAT)){
					for(Session s:sessionMap.values()){
						ChatMessage freshName=new ChatMessage();
						byte[] bs=new byte[msg.getContent().limit()];
						byte[] bs2=msg.getContent().array();
						System.arraycopy(bs2, 0, bs, 0, bs.length);
						freshName.setType(ChatType.CHAT);
						freshName.setName(msg.getName());
						freshName.setMessage(msg.getMessage());
						freshName.setContent(ByteBuffer.wrap(bs));
						s.add(freshName);
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for(Session s:sessionMap.values()){
			s.write();
		}
	}

	public void endCallBack() {

	}

	public void setServer(AIOServer server) {
		this.server=server;
	}
	public AIOServer getServer() {
		return server;
	}

}
